package com.kaibes.web.status;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import com.kaibes.core.base.util.FileUtils;
import com.kaibes.web.filter.BasicInterceptor;
import com.kaibes.web.util.ResourceUtils;

@Component
public class StatusInterceptor implements BasicInterceptor {

    @Autowired
    private StatusConfig statusConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (request.getMethod().equals("GET")) {
            int status = response.getStatus();
            String uri = statusConfig.getStatusViewMap().get(status);
            if (uri != null) {
                if (uri.endsWith(".html")) {
                    Resource resource = ResourceUtils.findResource(uri);
                    if (resource != null) {
                        //包起来，这样异常会关闭资源，否则可能造成内存泄漏
                        if (!FileUtils.transferTo(resource.getFile(), response.getOutputStream())) {
                        	return true;
                        }
                    } else {
                        return true;
                    }
                } else {
                    response.sendRedirect(uri);
                }
                return false;
            }
        }
        return BasicInterceptor.super.preHandle(request, response, handler);
    }

}
